<template>
  <el-button round @click="openRelation"
             :loading="loading" :disabled="!enable">
    {{ button.buttonName }}
  </el-button>
</template>
<script setup>
import {DefaultMenuButton} from '@/components/form/DefaultFormDefinition';
import {computed, getCurrentInstance, shallowRef, toRaw, watchEffect} from 'vue';
import {isEmpty, isNotEmpty} from '@/utils/CommonUtils';
import {getAction} from '@/request/BaseRequest';

const internalInstance = getCurrentInstance();
const global = internalInstance.appContext.config.globalProperties;

const loading = shallowRef(false);
const emits = defineEmits(['reload']);
const props = defineProps({
  button: DefaultMenuButton,
  selections: {
    type: Array,
    default: () => [],
  },
  formDefinition: undefined
});
let formDefinitoin = undefined;

function openRelation() {
  if (isNotEmpty(props.button.processKey)) {
    //需要发起流程
    startFlow();
  } else {
    //不需要发起流程, 但需要新建单子
  }
}

function startFlow() {
  loadFormDefinitionFieldsForMenuButton().then(flow => {
    doStartFlow(flow);
  });
}

function doStartFlow(flow) {
  let url = `/plat/work/startProcess?action=add&fullScreen=1&flowId=${flow.id}&buttonId=${props.button.id}&relateIds=${getSelectionIds()}`;
  global.$windowManager.open(url, {
    title: props.button.buttonName,
    close: () => emits('reload')
  });
}

function getSelectionIds() {
  return toRaw(props.selections).map(s => s.id).toString();
}

function loadFormDefinitionFieldsForMenuButton() {
  return new Promise((success, err) => {
    loading.value = true;
    getAction('/flow/loadLastProcessDefinitionByKey', {processKey: props.button.processKey}).then(data => {
      loading.value = false;
      if (data.success) {
        let result = data.result;
        success(result);
      }
    });
  });
}

function doOpenRelation() {
  console.log(formDefinitoin);
  console.log(props.button);
  let url = `/plat/work/startProcess?action=add&fullScreen=1&flowId=${props.button.processDefinitionId}`;

}

watchEffect(() => {
  loadButtonRelations();
});

function loadButtonRelations() {

}

const enable = computed(() => {
  if (isEmpty(props.selections)) return false;
  if (props.selections.length === 0) return true;
  if (props.selections.length >= 1 && props.button.supportMultiple) return true;
  if (props.selections.length === 1 && !props.button.supportMultiple) return true;
  return false;
});
</script>